<template>
  <div class="pager-container">
    <div><slot name="action" /></div>
    <el-pagination
      :background="background"
      :layout="layout"
      :total="total"
      :page-size.sync="pageSize"
      :page-sizes="pageSizes"
      :current-page.sync="currentPage"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>
<script>
import { scrollTo } from '@/utils/scroll-to'
// 整体参数说明
// page 当前页码 默认1
// limit 每页显示数量 默认20
// totle 数据总条数
// pageSizes 可更改的页码数组 默认[10, 20, 30, 50]
// layout 排版布局 默认 'sizes, prev, pager, next, total'
// background 分页按钮背景色 默认true

// autoScroll参数说明
// scroll 表格获取新数据后是否滚动到顶部，默认true
// tableId 滚动对象默认是表格 元素为'.el-table' 若设置格式为#id或.class
// body 是否整体body滚动 默认false
// to 滚动到顶部位置 默认0
// duration 滚动的速度延迟 默认500 越小滚动越快
export default {
  props: {
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 20
    },
    total: {
      type: Number,
      default: 0
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 30, 50]
      }
    },
    layout: {
      type: String,
      default: 'sizes, prev, pager, next, total'
    },
    background: {
      type: Boolean,
      default: true
    },
    autoScroll: {
      type: Object,
      default() {
        return {
          scroll: true, to: 0, duration: 500,
          tableId: '.el-table', body: false
        }
      }
    }
  },
  computed: {
    currentPage: {
      get() {
        return this.page
      },
      set(val) {
        this.$emit('update:page', val)
      }
    },
    pageSize: {
      get() {
        return this.limit
      },
      set(val) {
        this.$emit('update:limit', val)
      }
    }
  },
  methods: {
    handleSizeChange(val) {
      console.log(val)
      // 每页数量更改
      this.$emit('pageChange', { page: this.currentPage, limit: val })
    },
    handleCurrentChange(val) {
      // 页码更改
      this.$emit('pageChange', { page: val, limit: this.pageSize })
      var autoScroll = this.autoScroll
      if (autoScroll.scroll) {
        var elem = null
        if (!autoScroll.body) {
          elem = document.querySelector(autoScroll.tableId + ' .el-table__body-wrapper')
        }
        scrollTo({ to: autoScroll.to, elem: elem, duration: autoScroll.duration })
      }
    }
  }
}
</script>
<style lang="css">
  .pager-container{
    display: flex;flex-direction: row;justify-content: space-between;padding: 10px;
  }
</style>
